package com.zxlfysj.sort;

import java.util.Arrays;

/**
 * 插入排序
 * @author yangshujing
 * @create 2020-08-18 10:33
 */
public class InsertSort {
    public static void main(String[] args) {
        int[] arr = {3, 5, 6, 4, 2};
        insertSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void insertSort(int[] arr) {
        for(int i = 1; i < arr.length; i++) {
            int insertVal = arr[i];
            int insertIndex = i - 1;
            while(insertIndex >= 0 && insertVal < arr[insertIndex]) {
                arr[insertIndex + 1] = arr[insertIndex]; //还没找到位置，需要后移
                insertIndex--;
            }
            arr[insertIndex + 1] = insertVal;
        }
    }
}
